//
//  HJStartPageController.m
//  KaiChat
//
//  Created by lx on 2023/10/17.
//

#import "HJStartPageController.h"
#import "HJMinePresent.h"
#import "HJWebViewController.h"
#import "HJTitleTextField.h"
#import "QMUIButton.h"
#import "HJWebViewController.h"
#import "YYText.h"
#import "HJRegisterController.h"
#import "HJLoginController.h"
#import "HJGoogleAuthenticator.h"
#import "HJAppleAuthenticator.h"
#import "HJWebsiteFillter.h"

@interface HJStartPageController ()<HJAppleAuthenticatorDelegate>

@property (nonatomic, strong) UISwitch *switchView;
@property (nonatomic, assign) BOOL isAgreement;
@property (nonatomic, weak) HJStyle1Button *nextButton;
@property (nonatomic, weak) HJTitleTextField *emailTextField;
@property (nonatomic, weak) YYLabel *textLabel;
@property (nonatomic, strong) HJAppleAuthenticator *appleAuthenticator;
@property (nonatomic, weak) UIView *contentView;

@end

@implementation HJStartPageController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIScrollView *scrollView = [UIScrollView addToView:self.view];
    scrollView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight  - 110 - TabbarSafeBottomMargin);
    scrollView.backgroundColor = UIColor.tj_backgroundColor;
    CGSize contentSize = scrollView.bounds.size;

    scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    scrollView.contentSize = contentSize;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    UIView *contentView = [[UIView alloc] init].addTo(scrollView);
    contentView.backgroundColor = UIColor.tj_backgroundColor;
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
        make.width.offset(contentSize.width);
        make.height.offset(contentSize.height);
    }];
    
    
    UIImageView *logoImageView = [UIImageView addToView:contentView];
    logoImageView.contentMode = UIViewContentModeScaleAspectFill;
    logoImageView.image = [UIImage imageWithContentsOfName:@"login_top_bg" type:@"png"];
    CGFloat imageH = logoImageView.image.size.height * KScreenWidth / logoImageView.image.size.width;
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (isIPhoneX()) {
            make.top.offset(0);
        } else {
            make.top.offset(-30);
        }
        make.left.right.offset(0);
        make.height.offset(imageH);
    }];
    
    UIView *bottomView = [[UIView alloc] init].addTo(self.view);
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.height.offset(110 + TabbarSafeBottomMargin);
        make.left.right.offset(0);
    }];
    
    UIView *loginContentView = [[UIView alloc] init].addTo(contentView);
    loginContentView.backgroundColor = UIColor.whiteColor;
    [loginContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logoImageView.mas_bottom).offset(-18);
        make.left.right.bottom.offset(0);
    }];
   
    BOOL isRememberPassword = HJUserInfo.isRememberPassword;
    
    HJTitleTextField *emailTextField = [HJTitleTextField addToView:loginContentView];
    emailTextField.titleLabel.text = @"Email address";
    emailTextField.textField.placeholder = @"Enter your email address";
    emailTextField.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    if (isRememberPassword) {
        emailTextField.textField.text = HJUserInfo.email;
    }
    emailTextField.textField.keyboardType = UIKeyboardTypeASCIICapable;
    [emailTextField.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [emailTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(20);
        make.height.offset(82);
    }];
    
    UILabel *rememberPasswordLabel = [UILabel lableWithSuperView:loginContentView font:UIFontMake(12) color:UIColor.tj_868391Color title:@"Remember me" textAlignment:NSTextAlignmentLeft];
    [rememberPasswordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(emailTextField.mas_bottom).offset(6);
        make.left.equalTo(emailTextField);
    }];
    
    UISwitch *switchView = [UISwitch addToView:loginContentView];
    switchView.onTintColor = UIColor.tj_mainColor;
    switchView.on = isRememberPassword;
    [switchView addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
    switchView.transform = CGAffineTransformMakeScale(0.65, 0.65);
    [switchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(emailTextField);
        make.centerY.equalTo(rememberPasswordLabel);
    }];
    
    HJStyle1Button *nextButton = [HJStyle1Button buttonWithSuperView:loginContentView font:UIFontMediumMake(14) color:nil title:@"Next"];
    [nextButton addTarget:self action:@selector(didClickNextButton) forControlEvents:UIControlEventTouchUpInside];
    nextButton.enabled = NO;
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(20);
        make.height.offset(buttonHeight);
        make.top.equalTo(rememberPasswordLabel.mas_bottom).offset(20);
    }];
    
    QMUIButton *agreeButton = [QMUIButton addToView:loginContentView];
    [agreeButton addTarget:self action:@selector(didClickAgreeButton:) forControlEvents:UIControlEventTouchUpInside];
    [agreeButton setImage:[UIImage imageNamed:@"box_icon"] forState:UIControlStateNormal];
    [agreeButton setImage:[UIImage imageNamed:@"box_select_icon"] forState:UIControlStateSelected];
    [agreeButton setImagePosition:QMUIButtonImagePositionLeft];
    agreeButton.spacingBetweenImageAndTitle = 4;
    [agreeButton sizeToFit];
    [agreeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.height.offset(16);
        make.width.offset(16);
        make.top.equalTo(nextButton.mas_bottom).offset(15);
    }];
    
    YYLabel *textLabel = [[YYLabel alloc] initWithFrame:CGRectMake(10, KNavBarHight + 40, 200, 100)];
    textLabel.numberOfLines = 0;
    textLabel.font = UIFontMake(12);
    textLabel.textColor = UIColor.tj_868391Color;
    textLabel.backgroundColor = UIColor.clearColor;
    textLabel.preferredMaxLayoutWidth = KScreenWidth - 26 - leftRightMargin * 2;//最大宽度
    [loginContentView addSubview:textLabel];
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(agreeButton.mas_right).offset(5);
        make.top.equalTo(agreeButton);
        make.right.inset(leftRightMargin);
    }];
    
    NSString *contentString = @"I have read and accept the \"Terms of Service\" and \"Privacy Agreement\"";
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:contentString attributes:@{
        NSFontAttributeName: UIFontMake(12),
        NSForegroundColorAttributeName: UIColor.tj_868391Color
    }];
    
    TJWeakify(self)
    [attributedString yy_setTextHighlightRange:[contentString rangeOfString:@"I have read and accept the"] color:UIColor.tj_868391Color backgroundColor:UIColor.clearColor  tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakself didClickAgreeButton:agreeButton];
    }];
    
    [attributedString yy_setTextHighlightRange:[contentString rangeOfString:@"\"Terms of Service\""] color:UIColor.tj_333333Color backgroundColor:UIColor.clearColor  tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        HJWebViewController *webViewController = [[HJWebViewController alloc] init];
        webViewController.type = HJWebViewTypeService;
        webViewController.title = @"Terms of Service";
        [weakself.navigationController pushViewController:webViewController];
        
    }];
    [attributedString yy_setTextHighlightRange:[contentString rangeOfString:@"\"Privacy Agreement\""] color:UIColor.tj_333333Color backgroundColor:UIColor.clearColor  tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        HJWebViewController *webViewController = [[HJWebViewController alloc] init];
        webViewController.type = HJWebViewTypeService;
        webViewController.title = @"Terms of Service";
        [weakself.navigationController pushViewController:webViewController];
    }];
    
    textLabel.attributedText = attributedString;
    
    UILabel *quickLoginRegisterLabel = [UILabel lableWithSuperView:bottomView font:UIFontMake(12) color:UIColor.tj_BEBDCAColor title:@"Quick Login/Register" textAlignment:NSTextAlignmentLeft];
    [quickLoginRegisterLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.centerX.offset(0);
        make.height.offset(30);
    }];
    
    UIView *leftLineView = [UIView addToView:bottomView];
    leftLineView.backgroundColor = UIColor.tj_separatorColor;
    [leftLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.centerY.equalTo(quickLoginRegisterLabel);
        make.right.equalTo(quickLoginRegisterLabel.mas_left).inset(20);
        make.height.offset(lineHeight);
    }];
    
    UIView *rightLineView = [UIView addToView:bottomView];
    rightLineView.backgroundColor = UIColor.tj_separatorColor;
    [rightLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.centerY.equalTo(quickLoginRegisterLabel);
        make.left.equalTo(quickLoginRegisterLabel.mas_right).inset(20);
        make.height.offset(lineHeight);
    }];
    
    QMUIButton *googleButton = [QMUIButton buttonWithSuperView:bottomView font:UIFontMediumMake(14) color:UIColor.tj_333333Color title:@"Google"];
    [googleButton setImage:[UIImage imageNamed:@"google_logo_icon"] forState:UIControlStateNormal];
    googleButton.addCornerRadius(10);
    googleButton.layer.borderColor = UIColor.tj_333333Color.CGColor;
    googleButton.layer.borderWidth = 1;
    googleButton.backgroundColor = UIColor.whiteColor;
    googleButton.imagePosition = QMUIButtonImagePositionLeft;
    googleButton.spacingBetweenImageAndTitle = 10;
    [googleButton addTarget:self action:@selector(didClickGoogleButton) forControlEvents:UIControlEventTouchUpInside];

    if (isHiddenAppleServe()) {
        [googleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(quickLoginRegisterLabel.mas_bottom).offset(15);
            make.left.right.inset(leftRightMargin);
            make.height.offset(buttonHeight);
        }];
    } else {
        [googleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(quickLoginRegisterLabel.mas_bottom).offset(15);
            make.left.offset(leftRightMargin);
            make.right.equalTo(self.view.mas_centerX).inset(8);
            make.height.offset(buttonHeight);
        }];
        
        QMUIButton *appleButton = [QMUIButton buttonWithSuperView:bottomView font:UIFontMediumMake(14) color:UIColor.tj_333333Color title:@"Apple"];
        [appleButton setImage:[UIImage imageNamed:@"Apple_logo_icon"] forState:UIControlStateNormal];
        appleButton.addCornerRadius(10);
        appleButton.layer.borderColor = UIColor.tj_333333Color.CGColor;
        appleButton.layer.borderWidth = 1;
        appleButton.backgroundColor = UIColor.whiteColor;
        appleButton.imagePosition = QMUIButtonImagePositionLeft;
        appleButton.spacingBetweenImageAndTitle = 10;
        [appleButton addTarget:self action:@selector(didClickAppleButton) forControlEvents:UIControlEventTouchUpInside];
        [appleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(googleButton);
            make.right.inset(leftRightMargin);
            make.left.equalTo(self.view.mas_centerX).inset(8);
            make.height.offset(buttonHeight);
        }];
    }
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    loginContentView.layer.mask = [loginContentView shapeLayerRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight radius:20];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlerKeyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlerKeyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
    
    _emailTextField = emailTextField;
    _textLabel = textLabel;
    _nextButton = nextButton;
    _contentView = contentView;
    
    CGRect textLabelRect = [self.textLabel.superview convertRect:self.textLabel.frame toView:self.view];

    if (CGRectGetMaxY(textLabelRect) > KScreenHeight - (110 + TabbarSafeBottomMargin)) {
        contentSize = CGSizeMake(KScreenWidth, CGRectGetMaxY(textLabelRect));
        [contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
            make.width.offset(contentSize.width);
            make.height.offset(contentSize.height);
        }];
        scrollView.contentOffset = CGPointMake(0, CGRectGetMaxY(textLabelRect) - (KScreenHeight - (110 + TabbarSafeBottomMargin)));
    }
    
//    HJWebsiteFillter *websiteFillter = [[HJWebsiteFillter alloc] init];
//    [websiteFillter webMeta:@"https://www.zhihu.com"];

}

- (void)handlerKeyboardWillShowNotification:(NSNotification *)noti {
    
    CGRect textLabelRect = [self.textLabel.superview convertRect:self.textLabel.frame toView:self.view];
    CGRect keyboardFrame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    NSDictionary *userInfo = [noti userInfo];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    //先判断 textLabelRect的最大, 和键盘的最小y
     //如果健脾的最小y, 大于 textLabelRect 最大 就return
    //否则, 就修改scrollView位置
    CGFloat textLabelMaxY = CGRectGetMaxY(textLabelRect) + 10;
    CGFloat keyboardMinY = CGRectGetMinY(keyboardFrame);
    
    if (textLabelMaxY <= keyboardMinY) {
        return;
    }
    
    UIScrollView *scrollView = (UIScrollView *)self.contentView.superview;
    scrollView.scrollEnabled = NO;
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:duration animations:^{
        [scrollView setContentOffset:CGPointMake(0, textLabelMaxY - keyboardMinY)];
    } completion:^(BOOL finished) {
        scrollView.scrollEnabled = YES;
    }];
}

- (void)handlerKeyboardWillHideNotification:(NSNotification *)noti {

    NSDictionary *userInfo = [noti userInfo];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];//动画曲线类型
    [UIView setAnimationCurve:curve];
    
    UIScrollView *scrollView = (UIScrollView *)self.contentView.superview;

    [UIView animateWithDuration:duration animations:^{
        [scrollView setContentOffset:CGPointMake(0, 0)];
    } completion:^(BOOL finished) {
        scrollView.scrollEnabled = YES;
    }];
}

- (void)didClickGoogleButton {
    if (!_isAgreement) {
        [HJHUD showMessage:@"Please confirm the agreement before proceeding"];
        return;
    }
    [HJGoogleAuthenticator signInWithPresentingViewController:self completion:^(GIDGoogleUser * _Nonnull user, NSError * _Nonnull error) {
        
        if (error) {
            [HJHUD showMessage:error.localizedFailureReason];
            return;
        }
        
        [HJHUD showLoadingInView:self.view];
        [HJMinePresent googleLoginWithGoogleUserId:user.userID token:user.idToken.tokenString email:user.profile.email complete:^(NSError * _Nullable error) {//里面配置
            
        }];
    }];
    
}

- (void)didClickAppleButton {
    if (!_isAgreement) {
        [HJHUD showMessage:@"Please confirm the agreement before proceeding"];
        return;
    }
    [self.appleAuthenticator signInWithWithWindow:self.view.window];
}

- (void)didClickAgreeButton:(UIButton *)button {
    button.selected = !button.selected;
    _isAgreement = button.selected;
    
    [self textFieldDidChange:_emailTextField.textField];
}

- (void)didClickNextButton {
    
    NSString *email = _emailTextField.textField.text;
    
    if (![email.lowercaseString containsString:@"@"]) {
        [HJHUD showErrorMessage:@"Email format error"];
        return;
    }
    
    [self.view endEditing:YES];
    [HJHUD showLoadingInView:self.view];
    [HJMinePresent getAccountStatus:email complete:^(NSInteger status, NSError * _Nullable error) {
        if (error) {
            return;
        }
        //-1-注销|0-不存在|1-待激活|2-正常|3-禁用
        if (status == 0 || status == -1) {
            HJRegisterController *registerController = [[HJRegisterController alloc] init];
            registerController.email = self.emailTextField.textField.text;
            [self.navigationController pushViewController:registerController];
        } else if (status == 1 || status == 2) {
            HJLoginController *loginController = [[HJLoginController alloc] init];
            loginController.email = self.emailTextField.textField.text;
            [self.navigationController pushViewController:loginController];
        }
    }];
}


- (void)loadAgreementData {
    [HJMinePresent getAgreementComplete:nil];
}


- (void)switchValueChanged:(UISwitch *)switchView {
    HJTools.tool.isRememberPassword = switchView.isOn;
}

- (void)textFieldDidChange:(UITextField *)textField {
    _nextButton.enabled = !isEmptyString(_emailTextField.textField.text) && _isAgreement;
}

- (void)didClickRgistrationButton:(UIButton *)button {
    [self.navigationController pushViewControllerWithName:@"HJRegisterController"];
}

- (void)didClickEmailLoginButton {
    [self.navigationController pushViewControllerWithName:@"HJLoginController"];
}

- (HJAppleAuthenticator *)appleAuthenticator {
    if (!_appleAuthenticator) {
        _appleAuthenticator = [[HJAppleAuthenticator alloc] init];
        _appleAuthenticator.delegate = self;
    }
    return _appleAuthenticator;
}

- (void)appleAuthenticator:(HJAppleAuthenticator *)manager didCompleteWithError:(NSError *)error {
    NSLog(@"appleAuthenticatorerror = %@",error);
    [HJHUD showMessage:error.localizedFailureReason];
}

- (void)appleAuthenticator:(HJAppleAuthenticator *)manager didCompleteWithResult:(HJAppleSignInResult *)result {
    NSLog(@"didCompleteWithResult = %@",result);
    
    [HJHUD showLoadingInView:self.view];
    [HJMinePresent appleLoginWithAppleUserId:result.user.userID token:result.user.identityToken complete:^(NSError * _Nullable error) {//显示错误里面配置
        
    }];
}


- (void)appleAuthenticator:(HJAppleAuthenticator *)manager appleIdStateChanged:(NSDictionary *)info {
    NSLog(@"appleAuthenticator = %@",info);
}

- (BOOL)hiddenNavigationBar {
    return YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    IQKeyboardManager.sharedManager.enable = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    IQKeyboardManager.sharedManager.enable = YES;
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
